import { loginApi } from '@/api/auth';
import { LoginData } from '@/api/auth/model';
import { UserInfo } from "@/api/user/model";
import { store } from "@/store";

import { TOKEN_KEY } from '@/enums/CacheEnum'


export const useUserStore = defineStore("user", () => {
    const user = ref<UserInfo>({
        roles: [],
        perms: [],
    });

    /**
 * 登录调用
 *
 * @param {LoginData}
 * @returns
 */
    function login(loginData: LoginData) {
        return new Promise<void>((resolve, reject) => {
            loginApi(loginData)
                .then(response => {
                    const { tokenType, accessToken } = response.data;
                    localStorage.setItem(TOKEN_KEY, tokenType + " " + accessToken); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
                    resolve();
                })
                .catch(error => {
                    reject(error);
                });
        });
    }


    return {
        user,
        login,
    };
});

// 非setup
export function useUserStoreHook() {
    return useUserStore(store);
}
